package com.wolf.coder;

import com.wolf.core.Header;
import com.wolf.core.Protocol;
import com.wolf.core.RequestEntity;
import com.wolf.core.ResponseEntity;
import com.wolf.enums.Command;
import com.wolf.serialization.SerialFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @auth: dylan
 * @Desc:
 * @Time: 2024/4/30
 */
@Slf4j
public class WolfDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list) throws Exception {
        short magic = byteBuf.readShort();

        short command=byteBuf.readShort();

        byte serialType=byteBuf.readByte();

        int dataLength=byteBuf.readInt();

        Header header=Header.builder().magic(magic).command(command).serialType(serialType)
                .dataLength(dataLength).build();
        byteBuf.markReaderIndex();
        if(byteBuf.readableBytes()<dataLength){
            log.error("The decoder fail  dataLength unMatch");
            return;
        }
        byte [] bytes=new byte[dataLength];
        byteBuf.readBytes(bytes);
        if(command== Command.REQUEST.getCode()){
            Protocol<RequestEntity> protocol=new Protocol<>();
            protocol.setHeader(header);
            RequestEntity request = SerialFactory.get(header.getSerialType()).deSerializer(bytes, RequestEntity.class);
            protocol.setContent(request);
            list.add(protocol);
        }else {
            Protocol<ResponseEntity> protocol=new Protocol<>();
            protocol.setHeader(header);
            ResponseEntity response = SerialFactory.get(header.getSerialType()).deSerializer(bytes, ResponseEntity.class);
            protocol.setContent(response);
            list.add(protocol);
        }

    }
}
